package cn.xueden.util;

import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * @author:梁志杰
 * @date:2025/6/8
 * @description:cn.xueden.util
 * @version:1.0
 */
@Component
public class SecretUtils {

    /***
     * key和iv值可以随机生成
     */
    private static String KEY = "63eeac68cf074c8c";

    private static String IV = "63eeac68cf074c8c";

    /**
     * DES加密
     * @param data
     * @return
     */
    public static CharSequence desEncrypt(String data) {
        return desEncrypt(data, KEY, IV);
    }

    /**
     * 解密方法
     * @param data 要解密的数据
     * @param key  解密key
     * @param iv 解密iv
     * @return 解密的结果
     */
    private static String desEncrypt(String data, String key, String iv){
        try {
            byte[] encrypted1 = new Base64().decode(data);

            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "AES");
            IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
            byte[] original = cipher.doFinal(encrypted1);
            return new String(original).trim();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
